<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="55px">
      <el-form-item label="标题" prop="title" >
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入内容"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptId" >
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择部门"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in deptTreeOptions"
            :key="item.deptId"
            :label="item.label"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否可用" prop="status" label-width="80px">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择是否可用"
          clearable
          size="small"
          style="width: 150px"
        >
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:smsjob:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          v-hasPermi="['system:smsjob:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['system:smsjob:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:smsjob:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="smsjobList"
      @expand-change="handleExpandChange"
      ref="mainTable"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <div class="detail-container">
            <!-- 子表格操作按钮 -->
            <!-- <div class="detail-header">
              <el-row :gutter="10" class="detail-toolbar">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAddDeatil(props.row)"
                    v-hasPermi="['system:deatil:add']"
                  >新增回复</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="getDetailSingle(props.row.id)"
                    @click="handleUpdateDeatil(props.row)"
                    v-hasPermi="['system:deatil:edit']"
                  >修改回复</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="getDetailMultiple(props.row.id)"
                    @click="handleDeleteDeatil(props.row)"
                    v-hasPermi="['system:deatil:remove']"
                  >删除回复</el-button>
                </el-col>
              </el-row>
            </div> -->
            
            <div class="detail-content">
              <el-table
                :ref="'detailTable' + props.row.id"
                v-loading="props.row.deatilLoading"
                :data="props.row.deatilList || []"
                style="width: 100%"
                @selection-change="(selection) => handleDetailSelectionChange(selection, props.row)"
                class="detail-table"
                size="mini"
                border
              >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="回复内容" align="center" prop="content" min-width="200" show-overflow-tooltip />
                <el-table-column label="提交部门" align="center" prop="user" width="150">
                  <template slot-scope="scope">
                    <el-tooltip :content="getDeptNames(scope.row.user)" placement="top" effect="dark">
                      <span>{{ getDeptNamesEllipsis(scope.row.user) }}</span>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column label="文件列表" align="center" width="200">
                  <template slot-scope="scope">
                    <div v-if="scope.row.fileList && scope.row.fileList.length > 0" class="file-list-cell">
                      <div v-for="(file, index) in scope.row.fileList" :key="index" class="file-item-cell">
                        <a :href="file.filePath" target="_blank" class="file-link">{{ file.fileName }}</a>
                      </div>
                    </div>
                    <span v-else class="no-file-text">无</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="180" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-view"
                      @click="handleDetailDeatil(scope.row)"
                    >详情</el-button>
                    <el-button
                      v-if="scope.row.flag == 1"
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleReply(scope.row, true)"
                      v-hasPermi="['system:deatil:edit']"
                    >修改</el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDeleteSingleDeatil(scope.row, props.row)"
                      v-hasPermi="['system:deatil:remove']"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 子表格分页 -->
              <div class="detail-pagination">
                <pagination
                  v-show="props.row.deatilTotal > 0"
                  :total="props.row.deatilTotal"
                  :page.sync="props.row.deatilPageNum"
                  :limit.sync="props.row.deatilPageSize"
                  @pagination="(obj) => getDetailList(props.row, obj)"
                />
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="部门名称" align="center" prop="deptId">
        <template slot-scope="scope">
          <el-tooltip :content="getDeptNames(scope.row.deptId)" placement="top" effect="dark">
            <span>{{ getDeptNamesEllipsis(scope.row.deptId) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:smsjob:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:smsjob:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.flag == 1"
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="handleReply(scope.row)"
          >回复</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改smsjob对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="isDetailMode">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" :disabled="isDetailMode"/>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptId">
          <el-select
            v-model="form.deptId"
            multiple
            placeholder="请选择部门"
            filterable
            style="width: 100%"
            ref="deptSelect"
            :disabled="isDetailMode"
            @change="handleDeptSelectChange"
          >
            <el-option
              v-for="item in deptOptionsWithAll"
              :key="item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="附件" v-if="!isDetailMode">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="/dev-api/system/file/upload"
            :limit="5"
            :file-list="form.fileList"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件不超过500MB，最多上传5个文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <!-- 附件部分独立出来，不受表单disabled影响 -->
      <div style="margin-top: 20px;" v-if="isDetailMode">
        <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #606266;">附件</label>
        <div v-if="form.fileList && form.fileList.length > 0" class="file-list">
          <div v-for="(file, index) in form.fileList" :key="index" class="file-item">
            <el-button 
              type="text" 
              icon="el-icon-download"
              @click="downloadFile(file.url, file.name)"
            >
              {{ file.name }}
            </el-button>
          </div>
        </div>
        <span v-else class="no-file">无附件</span>
      </div>
    
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isDetailMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加任务回复对话框 -->
    <el-dialog :title="deatilTitle" :visible.sync="deatilOpen" width="500px" append-to-body>
      <el-form ref="deatilForm" :model="deatilForm" :rules="deatilRules" label-width="80px">
        <el-form-item label="内容" prop="content">
          <editor v-model="deatilForm.content" :min-height="192"/>
        </el-form-item>
        <!-- <el-form-item label="提交部门" prop="user">
          <el-select
            v-model="deatilForm.user"
            placeholder="请选择部门"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in deptTreeOptions"
              :key="item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="附件">
          <el-upload
            ref="deatilUpload"
            class="upload-demo"
            action="/dev-api/system/file/upload"
            :limit="5"
            :file-list="deatilForm.fileList"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleDeatilUploadSuccess"
            :on-remove="handleDeatilRemove"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">单个文件不超过500MB，最多上传5个文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeatilForm">确 定</el-button>
        <el-button @click="cancelDeatil">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 子表格详情对话框 -->
    <el-dialog :title="deatilDetailTitle" :visible.sync="deatilDetailOpen" width="500px" append-to-body>
      <el-form ref="deatilDetailForm" :model="deatilDetailForm" label-width="80px" :disabled="true">
        <el-form-item label="内容" prop="content">
          <editor v-model="deatilDetailForm.content" :min-height="192" :disabled="true"/>
        </el-form-item>
        <el-form-item label="提交部门" prop="user">
          <el-select
            v-model="deatilDetailForm.user"
            placeholder="请选择部门"
            filterable
            style="width: 100%"
            :disabled="true"
          >
            <el-option
              v-for="item in deptTreeOptions"
              :key="item.deptId"
              :label="item.label"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <!-- 附件部分独立出来，不受表单disabled影响 -->
      <div style="margin-top: 20px;">
        <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #606266;">附件</label>
        <div v-if="deatilDetailForm.fileList && deatilDetailForm.fileList.length > 0" class="file-list">
          <div v-for="(file, index) in deatilDetailForm.fileList" :key="index" class="file-item">
            <el-button 
              type="text" 
              icon="el-icon-download"
              @click="downloadFile(file.url, file.name)"
            >
              {{ file.name }}
            </el-button>
          </div>
        </div>
        <span v-else class="no-file">无附件</span>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDeatilDetail">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSmsjob, getSmsjob, delSmsjob, addSmsjob, updateSmsjob, exportSmsjobWithFiles } from "@/api/smsjob/smsjob";
import { listDept } from "@/api/system/dept";
import { listDeatil, getDeatil, delDeatil, addDeatil, updateDeatil } from "@/api/deatil/deatil";

export default {
  name: "Smsjob",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // smsjob表格数据
      smsjobList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        deptId: null,
        status: "Y"
      },
      // 表单参数
      form: {
        id: null,
        title: null,
        content: null,
        deptId: [],
        fileList: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      },
      // 表单校验
      rules: {
      },
      deptTreeOptions: [],
      // 任务回复相关数据
      deatilOpen: false,
      deatilTitle: "",
      currentdataId: null,
      deatilForm: {
        id: null,
        dataId: null,
        content: null,
        user: null,
        fileList: []
      },
      deatilRules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        user: [
          { required: true, message: "提交部门不能为空", trigger: "change" }
        ]
      },
      defaultDeatilPageSize: 10, // 子表格默认每页条数
      selectedDetails: {}, // 存储每个主表格行对应的子表格选中项
      isDetailMode: false, // 控制表单的只读模式
      deatilDetailTitle: "",
      deatilDetailOpen: false,
      deatilDetailForm: {
        id: null,
        dataId: null,
        content: null,
        user: null,
        fileList: []
      },
    };
  },
  computed: {
    deptOptionsWithAll() {
      return [
        { deptId: -1, label: '全部', value: -1 },
        ...this.deptTreeOptions
      ];
    }
  },
  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    /** 查询任务下发列表 */
    getList() {
      this.loading = true;
      listSmsjob(this.queryParams).then(response => {
        this.smsjobList = response.rows.map(item => ({
          ...item,
          deatilList: [],
          deatilLoading: false,
          isLoaded: false,
          deatilPageNum: 1,
          deatilPageSize: this.defaultDeatilPageSize,
          deatilTotal: 0
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 处理展开/收起操作 */
    handleExpandChange(row, expandedRows) {
      if (expandedRows.length > 0) {
        // 展开时
        if (!row.isLoaded) {
          // 首次展开，加载数据
          this.getDetailList(row).then(() => {
            // 数据加载完成，恢复勾选状态
            this.restoreDetailSelection(row);
          });
        } else {
          // 再次展开，直接恢复勾选状态
          this.$nextTick(() => {
            this.restoreDetailSelection(row);
          });
        }
      } else {
        // 收起时，保存当前的勾选状态
        this.saveDetailSelection(row);
      }
    },
    /** 获取详情列表 */
    getDetailList(row, pagination) {
      if (pagination) {
        row.deatilPageNum = pagination.page;
        row.deatilPageSize = pagination.limit;
      }
      row.deatilLoading = true;
      return listDeatil({
        dataId: row.id,
        pageNum: row.deatilPageNum,
        pageSize: row.deatilPageSize
      }).then(response => {
        row.deatilList = response.rows.map(item => ({
          ...item,
          flag: item.flag || 0
        }));
        row.deatilTotal = response.total;
        row.isLoaded = true;
        return response;
      }).finally(() => {
        row.deatilLoading = false;
      });
    },
    /** 子表格选择事件 */
    handleDetailSelectionChange(selection, parentRow) {
      if (!this.selectedDetails[parentRow.id]) {
        this.$set(this.selectedDetails, parentRow.id, []);
      }
      this.selectedDetails[parentRow.id] = selection;
    },
    // 保存子表格勾选状态
    saveDetailSelection(row) {
      const detailTable = this.$refs['detailTable' + row.id];
      if (detailTable && detailTable[0]) {
        // 获取当前选中的行
        const currentSelection = detailTable[0].selection || [];
        this.selectedDetails[row.id] = [...currentSelection];
        console.log('保存勾选状态:', row.id, currentSelection.length);
      }
    },
    // 恢复子表格勾选状态
    restoreDetailSelection(row) {
      const detailTable = this.$refs['detailTable' + row.id];
      const savedSelection = this.selectedDetails[row.id] || [];
      
      if (detailTable && detailTable[0] && savedSelection.length > 0) {
        // 恢复之前的勾选状态
        savedSelection.forEach(selectedItem => {
          const matchingRow = row.deatilList.find(item => item.id === selectedItem.id);
          if (matchingRow) {
            detailTable[0].toggleRowSelection(matchingRow, true);
          }
        });
        console.log('恢复勾选状态:', row.id, savedSelection.length);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isDetailMode = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        deptId: [],
        fileList: [],
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      // 重置上传组件
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.status = "Y"; // 重置后保持默认值
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isDetailMode = false;
      this.open = true;
      this.title = "添加smsjob";
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      if (!row || !row.id) {
        this.$message.warning('请选择要查看的数据行');
        return;
      }
      this.reset();
      this.isDetailMode = true;
      const id = row.id;
      // 先获取部门列表
      this.getDeptList().then(() => {
        // 再获取数据详情
        getSmsjob(id).then(response => {
          const data = response.data;
          this.form = {
            ...data,
            deptId: data.deptId ? data.deptId.split(',').map(id => parseInt(id)) : [], // 确保转换为数字类型
            fileList: (data.fileList || []).map(file => ({
              name: file.fileName,
              url: file.filePath
            }))
          };
          this.open = true;
          this.title = "查看smsjob详情";
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row || !row.id) {
        this.$message.warning('请选择要修改的数据行');
        return;
      }
      this.reset();
      this.isDetailMode = false;
      const id = row.id;
      // 先获取部门列表
      this.getDeptList().then(() => {
        // 再获取数据详情
        getSmsjob(id).then(response => {
          const data = response.data;
          this.form = {
            ...data,
            deptId: data.deptId ? data.deptId.split(',').map(id => parseInt(id)) : [], // 确保转换为数字类型
            fileList: (data.fileList || []).map(file => ({
              name: file.fileName,
              url: file.filePath
            }))
          };
          this.open = true;
          this.title = "修改smsjob";
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取上传组件的文件列表最新状态
          const uploadRef = this.$refs.upload;
          let currentFileList = [];
          
          if (uploadRef && uploadRef.uploadFiles) {
            // 如果有上传组件，使用上传组件的文件列表
            currentFileList = uploadRef.uploadFiles.map(file => ({
              fileName: file.name,
              filePath: file.response ? file.response.data.url : file.url
            }));
          } else {
            // 如果没有上传组件，使用表单中的文件列表
            currentFileList = this.form.fileList.map(file => ({
              fileName: file.name,
              filePath: file.url
            }));
          }
          
          // 处理文件列表数据和部门ID
          const submitData = {
            ...this.form,
            deptId: Array.isArray(this.form.deptId)
              ? this.form.deptId.filter(id => id !== -1).join(',')
              : this.form.deptId,
            fileList: currentFileList
          };

          if (this.form.id != null) {
            updateSmsjob(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSmsjob(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (!row || !row.id) {
        this.$message.warning('请选择要删除的数据行');
        return;
      }
      const id = row.id;
      this.$modal.confirm('是否确认删除smsjob编号为"' + id + '"的数据项？').then(function() {
        return delSmsjob(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 构建导出参数
      const exportParams = {
        ...this.queryParams
      };
      
      // 调用导出接口
      exportSmsjobWithFiles(exportParams).then(response => {
        // 创建下载链接
        const blob = new Blob([response], { type: 'application/zip' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `任务下发数据_${new Date().getTime()}.zip`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        
        this.$modal.msgSuccess("导出成功");
      }).catch(error => {
        this.$modal.msgError("导出失败：" + error.message);
      });
    },
    getDeptList() {
      return listDept().then(response => {
        this.deptTreeOptions = this.handleDeptOptions(response.data);
        return this.deptTreeOptions; // 返回处理后的数据
      });
    },
    handleDeptOptions(depts) {
      const deptMap = {};
      depts.forEach(dept => {
        deptMap[dept.deptId] = dept;
      });
      const options = [];
      depts.forEach(dept => {
        let fullName = dept.deptName;
        let parentId = dept.parentId;
        while (parentId !== 0 && deptMap[parentId]) {
          const parent = deptMap[parentId];
          fullName = parent.deptName + '/' + fullName;
          parentId = parent.parentId;
        }
        options.push({
          deptId: parseInt(dept.deptId), // 确保ID是数字类型
          label: fullName,
          value: parseInt(dept.deptId)  // 确保ID是数字类型
        });
      });
      options.sort((a, b) => a.label.localeCompare(b.label));
      return options;
    },
    selectedDeptNames() {
      if (!this.form.deptId || this.form.deptId.length === 0) return '';
      return this.deptTreeOptions
        .filter(opt => this.form.deptId.includes(opt.deptId))
        .map(opt => opt.label)
        .join('，');
    },
    /** 文件上传相关方法 */
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 500;
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 500MB!');
        return false;
      }
      return true;
    },
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 直接使用完整的文件列表更新
        this.form.fileList = fileList.map(item => ({
          name: item.name,
          url: item.response ? item.response.data.url : item.url
        }));
        this.$message.success('文件上传成功');
      } else {
        this.$message.error('文件上传失败');
      }
    },
    handleRemove(file, fileList) {
      const fileName = file.name;
      this.$http.delete(`/system/file/delete?fileName=${fileName}`).then(response => {
        if (response.data.code === 200) {
          // 直接使用完整的文件列表更新
          this.form.fileList = fileList.map(item => ({
            name: item.name,
            url: item.response ? item.response.data.url : item.url
          }));
          this.$message.success('文件删除成功');
        } else {
          this.$message.error('文件删除失败');
        }
      });
    },
    // 获取完整的部门名称列表
    getDeptNames(deptIds) {
      if (!deptIds) return '';
      // 如果是单个ID（数字或字符串），直接查找对应的部门名称
      if (typeof deptIds === 'number' || (typeof deptIds === 'string' && !deptIds.includes(','))) {
        const dept = this.deptTreeOptions.find(item => item.deptId == deptIds);
        return dept ? dept.label : deptIds;
      }
      // 如果是多个ID（逗号分隔），按原来的逻辑处理
      const deptIdList = deptIds.split(',');
      return deptIdList.map(deptId => {
        const dept = this.deptTreeOptions.find(item => item.deptId == deptId);
        return dept ? dept.label : deptId;
      }).join('，');
    },
    // 获取截断的部门名称列表（固定长度）
    getDeptNamesEllipsis(deptIds) {
      const fullNames = this.getDeptNames(deptIds);
      return fullNames.length > 15 ? fullNames.substring(0, 15) + '...' : fullNames;
    },
    // 回复按钮点击事件
    handleReply(row, isEdit = false) {
      this.resetDeatilForm();
      if (isEdit) {
        // 如果是修改操作，需要加载现有数据
        getDeatil(row.id).then(response => {
          const data = response.data;
          this.deatilForm = {
            ...data,
            fileList: (data.fileList || []).map(file => ({
              name: file.fileName,
              url: file.filePath
            }))
          };
        });
      } else {
        // 新增回复时只需要设置关联ID
        this.deatilForm.dataId = row.id;
      }
      this.deatilOpen = true;
      this.deatilTitle = isEdit ? "修改回复" : "回复任务";
    },
    // 重置回复表单
    resetDeatilForm() {
      this.deatilForm = {
        id: null,
        dataId: null,
        content: null,
        user: null,
        fileList: []
      };
      this.resetForm("deatilForm");
    },
    // 取消回复
    cancelDeatil() {
      this.deatilOpen = false;
      this.resetDeatilForm();
    },
    // 提交回复表单
    submitDeatilForm() {
      this.$refs["deatilForm"].validate(valid => {
        if (valid) {
          const uploadRef = this.$refs.deatilUpload;
          const currentFileList = uploadRef ? uploadRef.uploadFiles : [];
          
          const submitData = {
            ...this.deatilForm,
            fileList: currentFileList.map(file => ({
              fileName: file.name,
              filePath: file.response ? file.response.data.url : file.url
            }))
          };

          if (this.deatilForm.id != null) {
            updateDeatil(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.deatilOpen = false;
              this.getList();
            });
          } else {
            addDeatil(submitData).then(response => {
              this.$modal.msgSuccess("回复成功");
              this.deatilOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    // 回复的文件上传成功处理
    handleDeatilUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.deatilForm.fileList = fileList.map(item => ({
          name: item.name,
          url: item.response ? item.response.data.url : item.url
        }));
        this.$message.success('文件上传成功');
      } else {
        this.$message.error('文件上传失败');
      }
    },
    // 回复的文件删除处理
    handleDeatilRemove(file, fileList) {
      const fileName = file.name;
      this.$http.delete(`/system/file/delete?fileName=${fileName}`).then(response => {
        if (response.data.code === 200) {
          this.deatilForm.fileList = fileList.map(item => ({
            name: item.name,
            url: item.response ? item.response.data.url : item.url
          }));
          this.$message.success('文件删除成功');
        } else {
          this.$message.error('文件删除失败');
        }
      });
    },
    /** 子表格详情按钮操作 */
    handleDetailDeatil(row) {
      if (!row || !row.id) {
        this.$message.warning('请选择要查看的数据行');
        return;
      }
      this.resetDeatilDetailForm();
      // 获取详情数据
      getDeatil(row.id).then(response => {
        const data = response.data;
        this.deatilDetailForm = {
          ...data,
          fileList: (data.fileList || []).map(file => ({
            name: file.fileName,
            url: file.filePath
          }))
        };
        this.deatilDetailTitle = "查看回复详情";
        this.deatilDetailOpen = true;
      });
    },
    // 重置子表格详情表单
    resetDeatilDetailForm() {
      this.deatilDetailForm = {
        id: null,
        dataId: null,
        content: null,
        user: null,
        fileList: []
      };
      this.resetForm("deatilDetailForm");
    },
    // 取消子表格详情
    cancelDeatilDetail() {
      this.deatilDetailOpen = false;
      this.resetDeatilDetailForm();
    },
    // 单个删除回复操作
    handleDeleteSingleDeatil(row, parentRow) {
      this.$modal.confirm('是否确认删除该回复？').then(function() {
        return delDeatil(row.id);
      }).then(() => {
        this.getDetailList(parentRow);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 文件下载方法
    downloadFile(url, fileName) {
      if (!url) {
        this.$message.error('文件路径不存在');
        return;
      }
      
      try {
        // 处理相对路径，添加基础URL
        let downloadUrl = url;
        if (!url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith('/')) {
          downloadUrl = '/dev-api' + url;
        }
        
        // 创建一个隐藏的a标签来下载文件
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = fileName || 'download';
        link.target = '_blank'; // 在新窗口打开，避免页面跳转
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$message.success('文件下载已开始');
      } catch (error) {
        console.error('文件下载失败:', error);
        this.$message.error('文件下载失败，请稍后重试');
      }
    },
    // 获取指定父行的子表格选中状态 - 单个选中
    getDetailSingle() {
      return (parentId) => {
        const selectedRows = this.selectedDetails[parentId] || [];
        return selectedRows.length !== 1;
      };
    },
    // 获取指定父行的子表格选中状态 - 多个选中
    getDetailMultiple() {
      return (parentId) => {
        const selectedRows = this.selectedDetails[parentId] || [];
        return !selectedRows.length;
      };
    },
    handleDeptSelectChange(val) {
      // 如果选了“全部”
      if (val.includes(-1)) {
        // 选中全部部门
        this.form.deptId = this.deptTreeOptions.map(item => item.deptId).concat(-1);
      } else {
        // 如果全选了所有部门，也自动加上“全部”
        const allDeptIds = this.deptTreeOptions.map(item => item.deptId);
        if (allDeptIds.length > 0 && allDeptIds.every(id => val.includes(id)) && !val.includes(-1)) {
          this.form.deptId = allDeptIds.concat(-1);
        } else {
          // 只要没全选，去掉“全部”
          this.form.deptId = val.filter(id => id !== -1);
        }
      }
    }
  }
};
</script>

<style scoped>
.el-table .el-table {
  margin-top: 10px;
  margin-bottom: 10px;
}
.pagination-container {
  margin-top: 10px;
  margin-bottom: 10px;
  text-align: right;
}
.detail-container {
  margin: 10px 50px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.detail-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-toolbar {
  margin-bottom: 0;
}

.detail-content {
  margin-bottom: 15px;
}

.detail-table {
  margin-bottom: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.detail-table .el-table__header-wrapper {
  background-color: #f5f7fa;
}

.detail-table .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

.detail-pagination {
  margin-top: 15px;
  padding: 10px 0;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

.file-list-cell {
  max-height: 120px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 6px;
  background-color: #f5f7fa;
}

.file-item-cell {
  margin-bottom: 4px;
  padding: 2px 0;
}

.file-item-cell:last-child {
  margin-bottom: 0;
}

.file-item-cell .file-link {
  color: #409eff;
  text-decoration: none;
  font-size: 12px;
  display: block;
  padding: 2px 4px;
  border-radius: 2px;
  transition: background-color 0.3s;
}

.file-item-cell .file-link:hover {
  background-color: #ecf5ff;
  color: #66b1ff;
}

.no-file-text {
  color: #909399;
  font-style: italic;
  font-size: 12px;
}

/* 确保分页组件不会被遮挡 */
.el-table__expanded-cell {
  padding: 0 !important;
}

/* 调整展开行的样式 */
.el-table .el-table__expanded-cell[class*=cell] {
  padding: 0;
}

/* 确保内容区域有足够的空间 */
.el-table .el-table__body td.el-table__expanded-cell {
  min-height: 100px;
}
</style>
